// 银行月结单

import creditImg from '@/assets/credit.png';
import subtract from '@/assets/subtract.png';
import icon from '@/assets/upload_icon.png';
import { getLinksStatements, getLinksUrl } from '@/services/login';
import { useGetToken } from '@/utils/request';
import type { GetProp, UploadProps } from 'antd';
import { Button, Col, Divider, Modal, Row, Space, Upload, message } from 'antd';
import { useEffect, useState } from 'react';
import { useIntl, useModel } from 'umi';
const { Dragger } = Upload;
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

type Props = {
  visible: boolean;
  handleCancel: () => void;
  value: any;
  onChange: (value: Record<string, any>) => void;
  disabled?: boolean;
};
const BankModal: React.FC<Props> = ({
  visible,
  handleCancel,
  value = [],
  onChange,
  disabled = false,
}) => {
  const intl = useIntl();
  const [iframeVisible, setIframeVisible] = useState(false);
  const { uploadParams } = useModel('uploadModel');
  const { statementsConfirmFlag } = uploadParams;
  const [val, setVal] = useState<any[]>([]);
  const { token, urlAction } = useGetToken();
  const [data, setData] = useState<{
    url: string;
    customerToken: string;
    code?: string;
  }>({
    url: '',
    customerToken: '',
    code: '',
  });
  const { url, customerToken } = data;
  const receiveMessage = async (data: any) => {
    if (data.origin.includes('xlend') && iframeVisible) {
      setIframeVisible(false);
      const { code } = await getLinksStatements({ code: data.data, token: customerToken });
      if (code == '100200') {
        handleCancel();
        onChange({
          statementsConfirmFlag: 'success',
        });
        message.success(intl.formatMessage({ id: 'login.credit.ok' }));
      }
    }
  };
  useEffect(() => {
    if (visible) {
      setVal(value);
    }
    // 监听三方回调后的code
    window.addEventListener('message', receiveMessage, false);
    return () => {
      window.removeEventListener('message', receiveMessage, false);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value, visible, data]);

  const beforeUpload = (file: FileType) => {
    const isLt20M = file.size / 1024 / 1024 < 20;
    if (!isLt20M) {
      message.error(intl.formatMessage({ id: 'home.live_max' }));
    }
    return isLt20M || Upload.LIST_IGNORE;
  };

  return (
    <Modal
      className="live bank"
      footer={false}
      width={660}
      closeIcon={null}
      open={visible}
      destroyOnClose
    >
      <div style={{ fontWeight: 'bold', fontSize: 23 }}>
        {intl.formatMessage({ id: 'home.bank_title' })}
      </div>
      <div style={{ color: '#999', margin: '10px 0 24px' }}>
        {intl.formatMessage({ id: 'home.bank_word' })}
      </div>
      <div style={{ marginBottom: 10 }}> {intl.formatMessage({ id: 'home.bank_credit' })}</div>
      <div className="bank_credit">
        <img src={creditImg} width={287} />
        <div style={{ color: '#666', margin: '10px 0 24px 0' }}>
          {intl.formatMessage({ id: 'home.bank_word' })}
        </div>

        <Button
          disabled={disabled}
          className="bank_btn default_btn"
          onClick={async () => {
            const { data } = await getLinksUrl();
            setIframeVisible(true);
            setData(data);
          }}
        >
          <Space size={12} align="center">
            <img src={subtract} width={18} />
            {intl.formatMessage({
              id: statementsConfirmFlag ? 'home.bank_credited' : 'home.bank_now',
            })}
          </Space>
        </Button>
      </div>
      <Divider className="bank_divider">
        <span style={{ color: '#666' }}>{intl.formatMessage({ id: 'home.bank_or' })}</span>
      </Divider>
      <div style={{ marginBottom: 10 }}> {intl.formatMessage({ id: 'home.bank_upload' })}</div>
      <Dragger
        maxCount={10}
        multiple
        accept=".jpg,.png,.pdf,.jpeg"
        disabled={disabled}
        action={urlAction}
        headers={{ Authorization: `Bearer ${token}` }}
        onChange={(info) => {
          let newFileList = [...info.fileList];
          newFileList = newFileList.map((file) => {
            const { status, response, url = '' } = file;

            if (status == 'done' && !url) {
              if (response?.code == '100200') {
                file.url = file.response.data;
              } else {
                file.status = 'error';
                message.error({
                  key: 'update',
                  content: response?.message || 'error',
                });
              }
            }
            return file;
          });
          setVal(newFileList);
        }}
        fileList={val}
        listType="text"
        beforeUpload={beforeUpload}
        style={{ padding: '24px 0' }}
      >
        <img src={icon} width={50} />
        <div style={{ marginTop: 16 }}>{intl.formatMessage({ id: 'home.dorp' })}</div>
        <div style={{ color: '#999' }}>{intl.formatMessage({ id: 'home.live' })}</div>
      </Dragger>
      <Row gutter={[24, 0]} style={{ marginTop: 40 }} justify="center">
        <Col span={12}>
          <Button
            onClick={handleCancel}
            style={{ width: '100%', background: '#F4F4F4', height: '60px', border: 'none' }}
          >
            {intl.formatMessage({ id: 'home.cancel' })}
          </Button>
        </Col>
        {!disabled && (
          <Col
            span={12}
            onClick={() => {
              // 如果有值，说明最后一次是上传
              onChange({
                bankMonthlyStatement: val,
              });

              handleCancel();
            }}
          >
            <Button style={{ width: '100%', height: '60px' }} type="primary">
              {intl.formatMessage({ id: 'home.sure' })}
            </Button>
          </Col>
        )}
      </Row>
      <Modal
        width={600}
        onCancel={() => {
          setIframeVisible(false);
        }}
        okButtonProps={{ style: { display: 'none' } }}
        open={iframeVisible}
      >
        <iframe src={url} style={{ width: '500px', height: '100vh' }} />
      </Modal>
    </Modal>
  );
};

export default BankModal;
